<template>
    <div>
        <el-col>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    >新增</el-button
                    >
                </el-col>
                </el-row>
                <el-form :model="form" ref="form">
                <el-table v-loading="loading" :data="thicknessList">
                    <el-table-column label="序号" align="center" width="80">
                    <template slot-scope="scope">
                        <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize +
                        scope.$index +
                        1
                        }}</span>
                    </template>
                    </el-table-column>
                    <el-table-column label="过纸区间(丝)" align="center" class-name="text-center">
                    <template slot-scope="scope">
                        <el-form-item align="center">
                            <template>
                                <el-input
                                    class="custom-input"
                                    maxlength="5"
                                    v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                                    v-model="form.paperFeedRangeStart"
                                    placeholder="请输入起始值"
                                    @change="validateCurrentRow"
                                ></el-input>
                                <span v-else>{{ scope.row.paperFeedRangeStart }}</span>
                            </template>
                            <span class="unit-text"> < 过纸 <= </span>
                            <template>
                                <el-input
                                    class="custom-input"
                                    maxlength="5"
                                    v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                                    v-model="form.paperFeedRangeEnd"
                                    placeholder="请输入结束值"
                                    @change="validateCurrentRow"
                                ></el-input>
                                
                                <span v-else>{{ scope.row.paperFeedRangeEnd }}</span>
                            </template>
                        </el-form-item>
                    </template>
                    </el-table-column>
                    <el-table-column
                    label="操作"
                    align="center"
                    width="150"
                    class-name="small-padding fixed-width"
                    >
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-if="scope.row.id && !isEdit"
                        >删除</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-check"
                        @click="editForm(scope.row)"
                        v-if="!isEdit"
                        >编辑</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-check"
                        @click="submitForm"
                        v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                        >保存</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-close"
                        @click="handleCancel(scope.row)"
                        v-if="!scope.row.id || (isEdit && scope.row.id==rowid)"
                        >取消</el-button
                        >
                    </template>
                    </el-table-column>
                </el-table>
                </el-form>
        </el-col>
    </div>
</template>
<script>

import {
  listPrintersColor,
  addColor,
  updateColor,
  delColor,
} from "@/api/base/digitalPrinters";

export default {
    props:{
        printerId: String,
        parentId: String,
    },
    data() {
        return {
            //加载状态
            loading: true,
            //是否可编辑
            isEdit: false,
            rowid: '',
            total:0,
            //厚度列表数据
            thicknessList: [],
            

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            }, 
            form: {
                paperFeedRangeStart: '',
                paperFeedRangeEnd: '',
            },
            // 修改校验规则
            validateRules: {
                // 校验数字范围 0-9999
                checkNumberRange: (value) => {
                    const num = Number(value);
                    if (isNaN(num) || num < 0 || num > 9999) {
                        return '请输入0-9999的整数';
                    }
                    return '';
                },
                // 校验起始值不大于结束值
                checkStartEnd: (start, end) => {
                    if(!start || !end) return
                    start = Number(start);
                    end = Number(end);
                    if (start > end) {
                        return '起始值不能大于结束值';
                    }
                    return '';
                },
                // 校验区间不重叠
                checkRangeOverlap: (start, end, list, currentId) => {
                    start = Number(start);
                    end = Number(end);
                    
                    const isOverlap = list.some(item => {
                        if (currentId && item.id === currentId) return false;
                        const itemStart = Number(item.paperFeedRangeStart);
                        const itemEnd = Number(item.paperFeedRangeEnd);
                        return (start >= itemStart && start <= itemEnd) || 
                               (end >= itemStart && end <= itemEnd) ||
                               (start <= itemStart && end >= itemEnd);
                    });
                    
                    return isOverlap ? '区间不能与其他记录重叠' : '';
                }
            }
        }
    },

    created() {
        this.getList();
    },
    methods: {
        //输入框正则校验
        validateInput(value) {
            if (value < 0 || value > 99999) {
                this.$modal.msgError("请输入0-99999之间数值!");
            }
        },
        //新增一行
        handleAdd(){
            if(this.isEdit){
                this.$modal.msgError("当前有正在编辑的数据, 请先保存后再新增");
                return
            }
            this.isEdit = true
            // 初始化form
            this.resetForm();

            // 判断之前的数据是否保存
            if (this.thicknessList.some((item) => item.paperFeedRangeStart == null)) {
                this.$modal.msgError("请先保存之前数据");
                return;
            }
            this.thicknessList.push({ wide: null });
        },
        //重置表单数据
        resetForm(){
            this.form = {
                paperFeedRangeStart: '',
                paperFeedRangeEnd: '',
            }
        },
        //获取厚度列表数据
        async getList(){
            try{
                this.loading = true
                this.queryParams = {
                    ...this.queryParams,
                    printerId: this.printerId,
                    parentId: this.parentId
                }

                const res = await listPrintersColor(this.queryParams);
                if(res && res.code===200){
                    this.thicknessList = res.rows
                    this.total = res.total
                }
            }catch(error){
                console.log('查询厚度列表出错',error)
            }finally{
                this.loading = false
            }
        },
        //删除
        handleDelete(row){
            this.$modal
                .confirm('是否确定删除信息？删除后数据将无法恢复，请谨慎操作')
                .then(function () {
                    return delColor(row.id);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                    this.$emit("reload-tree")
                })
                .catch(() => {});

        },
        editForm(row){
            this.isEdit = !this.isEdit
            this.rowid = row.id
            this.form = {
                ...this.form,
                id: row.id,
                paperFeedRangeStart: row.paperFeedRangeStart,
                paperFeedRangeEnd: row.paperFeedRangeEnd,
            }
        },
        //保存
        async submitForm(){
             // 提交前校验
            if (!this.validateCurrentRow()) {
                return;
            }
            try{
                this.form = {
                    ...this.form,
                    parentId: this.parentId,
                    printerId: this.printerId

                }
                let res = null;
                if(this.isEdit && this.rowid){//说明是编辑保存
                    res = await updateColor(this.form)
                }else{//说明是新增保存
                    res = await addColor(this.form)
                }
                if(res && res.code===200){
                    this.$modal.msgSuccess("保存成功");
                    this.$emit("reload-tree",this.parentId)
                    this.getList()
                }
            }catch(error){
                console.log('保存数据出错',error)
            }finally{
                this.isEdit = false
                this.rowid = ''
            }
            
        },
        //取消
        handleCancel(row){
            const id = row.id
            this.isEdit = false
            this.rowid = ''
            if(!id){//删除行
                this.thicknessList.splice(this.thicknessList.length - 1, 1);
            }
        },
        // 修改校验方法
        validateCurrentRow() {
            // 数字范围校验
            const startError = this.validateRules.checkNumberRange(this.form.paperFeedRangeStart);
            const endError = this.validateRules.checkNumberRange(this.form.paperFeedRangeEnd);
            
            if (startError) {
                this.$modal.msgError(`起始值${startError}`);
                return false;
            }
            if (endError) {
                this.$modal.msgError(`结束值${endError}`);
                return false;
            }
            
            // 新增：起始值不能大于结束值校验
            const startEndError = this.validateRules.checkStartEnd(
                this.form.paperFeedRangeStart,
                this.form.paperFeedRangeEnd
            );
            if (startEndError) {
                this.$modal.msgError(startEndError);
                return false;
            }
            
            // 区间校验
            const rangeError = this.validateRules.checkRangeOverlap(
                this.form.paperFeedRangeStart,
                this.form.paperFeedRangeEnd,
                this.thicknessList,
                this.rowid
            );
            
            if (rangeError) {
                this.$modal.msgError(rangeError);
                return false;
            }
            
            return true;
        },
    }
}
</script>
<style lang="scss" scoped>
    .custom-input {
        width: 30%;  /* 设置输入框宽度 */
    }
    .unit-text {
        font-size: 14px;
        color: #606266;
        margin-left: 5px;  /* 设置“毫米”文本的左边距 */
        margin-right: 5px; 
    }
    ::v-deep .text-center {
        .cell {
            display: flex;
            justify-content: center;
            align-items: center;
            vertical-align: middle;
            text-align: center;
        }
    }
</style>